const $ = (selector) => {
    return document.querySelector(selector)
}

let chunksList;
const BASE_URL = 'http://192.168.74.1:8000'
const defaultSplitSize = 1 * 1024 * 1024

$('#uploadFile').addEventListener('change', (e) => {
    console.log(e.target.files)
    chunksList = createChunks(e.target.files[0])
    $('#chunksText').innerHTML = `共切了${chunksList.length}片`
    console.log(chunksList, '12333');
})

$('#uploadStart').addEventListener('click', (e) => {
    // 点击开始上传， 利用Promise.all 函数进行上传
//     先对每一个切片进行封装，并利用 Promise.all进行上传，上传文件要用formData格式。对应的后端也要解析formData
//      切片上传之后，如果全部成功，则发起merge请求，通知后端进行合并
    uploadChunks().then((res) => {
        apiRequest('/merge', JSON.stringify({
            fileName: chunksList[0].filename,
            size: defaultSplitSize
        }))
    })
})

// 创建切片列表
const createChunks = (file, splitSize = defaultSplitSize) => {
    const chunks = []
    let cur = 0
    while(cur < file.size) {
        chunks.push({
            file: file.slice(cur, cur + splitSize),
            filename: file.name,
        })
        cur += splitSize
    }
    return chunks
}

const uploadChunks = () => {
    const reqList = chunksList.map((item, index) => {
        const formData = new FormData()
        formData.append('file', item.file)
        formData.append('index', index + '')
        formData.append('chunkName', `${item.filename}-${index}`)
        formData.append('fileName', item.filename)
        return formData
    }).map((data, index) => apiRequest('/upload', data, true).then(({ data }) => {
        if (data.code === 200) {
            $('#progress').innerHTML = `上传到：${index + 1},共${chunksList.length}片`
        }
    }))

    return Promise.all(reqList)
}

const apiRequest = (url, data, isForm) => {
    const config = {//设置请求头
        headers: `Content-Type:${isForm ? 'application/x-www-form-urlencoded' : 'application/json'}`
    }

    return new Promise((resolve, reject) => {
        window.axios.post(BASE_URL + url, data, config).then(res => {
            resolve(res)
        })
    })
}